// pages/myself/coupon/tenantCoupon.js
var Zan = require('../../../dist/index');
var coupon = require('../../../template/couponTemp.js');
let network = null;
let utils = null;
let api = null;
const app = getApp();
var start = 0;

Page(Object.assign({}, Zan.TopTips, Zan.Toast, {

  /**
   * 页面的初始数据
   */
  data: {
    coupon: [],
    myselft: 0,
    nodata: {
      msg: '没有可领取的优惠券',
      notype: 2,
      imgurl: '../../../images/nodatas.png',
      nourl: ''
    },
    isshowcoupon:0

  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    network = new app.NetWorkUtils();
    utils = new app.Utils();
    api = new app.Api();
    
    this.onPullDownRefresh();
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    start = 0;
    wx.stopPullDownRefresh();
    this.setData({
      coupon: [],
    });
    network._post_page_json(this, api.getTenntCouponList, start, {}, success);
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    if (this.data.coupon.length < this.data.recordsTotal) {
      start = start + 20;
      network._post_page_json(this, api.getTenntCouponList, start, {}, success);
    }
  },

  /**
   * 用户点击右上角分享
   */
  // onShareAppMessage: function () {

  // },
  // 查看优惠券详情
  couponDetails: function (e) {
    coupon.couponDetails(this, e);
  },

  // 领取优惠券
  receiveCoupon: function (e) {
    //coupon.receiveCoupon(this, e)
    var item = e.currentTarget.dataset.item;
    var couponId = [];
    couponId.push(item.id);
    network._post_json(this, api.receiveCoupon, { couponId }, success01);
  }
}))

// 获取优惠券列表结果
var success = function (that, res) {
  if (res.data.data) {
    var coupon = res.data.data;
    for (var i = 0; i < coupon.length; i++) {
      coupon[i].startTime = utils.formatDate02(new Date(coupon[i].startTime))
      coupon[i].endTime = utils.formatDate02(new Date(coupon[i].endTime))
      var couponId = [];
      couponId.push(coupon[i].id)

      // if (coupon[i].couponUse == null){
         coupon[i].isshow = 0
      // }else{
      //   coupon[i].isshow = 1
      // }
    
    }
    that.setData({
      coupon: that.data.coupon.concat(coupon),
      recordsTotal: res.data.recordsTotal
    })
  }
  
}

var success01 = function(that,res){
  that.showZanToast('领取成功');
}